<!--
 * @Author: zhayang
 * @LastEditors: zhayang 1063975710@qq.com
 * @Date: 2024-06-24 01:09:43
 * @LastEditTime: 2024-07-12 00:38:19
 * @Description:视频上传
-->
<template>
  <div class="avatar-uploader-box">
    <div
      v-if="videoPath != '' && !videoFlag"
      class="w-120 h-120 relative"
    >
      <video
        :src="videoPath"
        class="avatar video-avatar model-video fit"
        controls="controls"
      >
        您的浏览器不支持视频播放
      </video>
      <img
        :src="require('@/assets/images/model/video.png')"
        class="absolute w-33 h-33 cursor-pointer right-43 top-31"
        @click="playVideo"
      />
      <div
        class="absolute right-0 bottom-0 full-w h-34 bg-#00000080 center cursor-pointer text-#fff text-14"
        @click.stop="deleteVideo"
      >
        删除
      </div>
    </div>
    <el-upload
      v-else
      class="avatar-uploader"
      :class="{ 'cursor-not-allow': videoFlag }"
      drag
      :name="'filePath'"
      :multiple="false"
      :headers="postheaders"
      :data="postData"
      action="#"
      :disabled="videoFlag"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      accept=".mp4,.ogg,.flv,.avi,.wmv,.rmvb"
      :before-upload="beforeAvatarUpload"
      :http-request="handleUploadImg"
    >
      <i
        v-if="videoPath === '' && !videoFlag"
        class="el-icon-plus avatar-uploader-icon plus-icon"
      ></i>
      <div
        v-if="!videoFlag"
        class="up-text"
      >
        {{ upText }}
      </div>
    </el-upload>
    <el-dialog
      title="视频预览"
      :visible.sync="playState"
      custom-class="video-dialog"
      destroy-on-close
    >
      <video
        ref="VideoRef"
        :src="videoPath"
        class="pic-item full-w"
        controls
      ></video>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import { getToken } from '@/utils/auth'
import { getStsApi } from '@/api/upload'
export default {
  props: {
    url: {
      type: String,
      default: ''
    },
    // 地址是否完整
    integrityAddress: {
      type: String,
      default: '1'
    },
    upText: {
      type: String,
      default: ''
    },
    videoFlag: Boolean
  },
  data() {
    return {
      // 图片上传
      videoPath: '', // 视频地址
      imageUrl: '',
      postheaders: {
        'Auth-Token': getToken()
      },
      stsData: {},
      fileData: {},
      isShowUploadVideo: false, // 显示上传按钮
      postData: {
        key: '',
        policy: '',
        OSSAccessKeyId: '',
        signature: '',
        'x-oss-security-token': '' // 使用STS签名时必传。
      },
      playState: false
    }
  },
  watch: {
    url: {
      handler(nv, oldName) {
        if (nv) {
          if (this.integrityAddress === '0') {
            if (nv.indexOf('http') !== -1) {
              this.videoPath = nv
            } else {
              this.videoPath = process.env.VUE_APP_FILE_API + nv
            }
          } else {
            this.videoPath = nv
          }
        } else {
          this.videoPath = ''
        }
      },
      immediate: true
    }
  },
  created() {
    this.setData()
  },
  methods: {
    generateUUID() {
      const timestamp = Date.now().toString(16)
      const random = Math.random().toString(16).slice(2)
      return `${timestamp}${random}`
    },
    setData() {
      getStsApi()
        .then((res) => {
          this.stsData = res.data
        })
        .catch(() => {})
    },
    // 截取上传文件后缀
    getSuffix(filename) {
      const pos = filename.lastIndexOf('.')
      let suffix = ''
      if (pos !== -1) suffix = filename.substring(pos)
      return suffix
    },
    handleAvatarSuccess(res, file) {
      this.$emit('getFile', this.videoPath)
    },
    beforeAvatarUpload(file) {
      this.fileData = file
      const isLt2M = file.size / 1024 / 1024 < 1024
      if (!isLt2M) {
        this.$message.error('上传视频大小不能超过 1024MB!')
      }
      return isLt2M
    },
    handleUploadImg(file) {
      const that = this
      const signature = this.stsData.mp.signature
      const ossAccessKeyId = this.stsData.body.AccessKeyId
      const policy = this.stsData.mp.policy
      const key =
        this.stsData.file_path +
        this.generateUUID() +
        '.' +
        this.getSuffix(file.file.name)
      const securityToken = this.stsData.body.SecurityToken
      const formData = new FormData()
      formData.append('name', file.file.name) // 文件名称
      formData.append('key', key) // 存储在oss的文件路径
      formData.append('OSSAccessKeyId', ossAccessKeyId) // //accessKeyId
      formData.append('policy', policy) // policy
      formData.append('Signature', signature) // 签名
      formData.append('x-oss-security-token', securityToken) // 使用STS签名时必传。
      formData.append('success_action_status', 200)
      formData.append('file', file.file, file.file.name) // 如果是base64文件，那么直接把base64字符串转成blob对象进行上传即可
      const reader = new FileReader()
      reader.readAsDataURL(file.file)
      try {
        reader.onload = (e) => {
          let video = document.createElement('video')
          video.src = e.target.result
          video.onloadeddata = () => {
            const canvas = document.createElement('canvas')
            canvas.width = video.videoWidth
            canvas.height = video.videoHeight
            const ctx = canvas.getContext('2d')
            ctx.fillRect(0, 0, canvas.width, canvas.height)
            ctx.drawImage(video, 0, 0, canvas.width, canvas.height)
            ctx.imageSmoothingEnabled = false
            const base64data = canvas.toDataURL('image/png')
            this.$emit('getImg', base64data, this.stsData)
            canvas.toBlob(async () => {
              video.pause()
              video = null
            }, 'image/png')
          }
          video.muted = false
          video.play()
        }
      } catch (e) {
        //
      }

      return new Promise((resolve, reject) => {
        axios
          .post(that.stsData.host, formData, {
            headers: {
              'Content-Type': 'multipart/form-data',
              'Auth-Token': getToken()
            }
          })
          .then((rep) => {
            // console.log('rep', rep)
            if (rep.status === 200) {
              that.videoPath = that.stsData.host + '/' + key
            }
            resolve(rep)
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    deleteVideo() {
      this.videoPath = ''
      this.$emit('getFile', '')
    },
    playVideo() {
      this.playState = true
      this.$nextTick(() => {
        this.$refs.VideoRef.play()
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.avatar-uploader-box {
  ::v-deep {
    .avatar-uploader .el-upload {
      width: 120px;
      height: 120px;
      line-height: 120px;
      border: 1px dashed #dcdcdc;
      border-radius: 6px;

      position: relative;
      overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
      border-color: #04d1b8;
    }

    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      text-align: center;
    }
    .avatar {
      width: 120px;
      height: 120px;
      display: block;
    }

    .iconfont {
      font-size: 28px;
      color: #8c939d;
      width: 120px;
      height: 120px;
      text-align: center;
    }

    .el-upload-dragger {
      width: 100%;
      height: 100%;
      border: 0;
      background-color: #f4f5f9;
      position: relative;
      display: flex;
      flex-direction: column;
      justify-content: center;
    }
  }
}
.plus-icon {
  font-size: 28px;
  font-weight: 600;
  color: #1c1f23 !important;
  text-align: center;
}

.up-show {
  color: #1c1f23;
}

.up-text {
  margin-top: 10px;
  font-weight: 400;
  font-size: 10px;
  color: #6a6b6c;
  line-height: 12px;
}
.sub-up-text {
  font-weight: 400;
  font-size: 10px;
  color: #6a6b6c;
  line-height: 12px;
}
.model-video {
  object-fit: cover;
}
.cursor-not-allow {
  ::v-deep .el-upload-dragger {
    cursor: not-allowed;
  }
}
.pic-item {
  aspect-ratio: 16 / 9;
}
</style>
<style>
.video-dialog {
  .el-dialog__body {
    padding-top: 0px;
  }
}
</style>
